<template>
  <div class="Main">
    <div class="MainTitle">订单详情</div>
    <div class="MianContent">

      <!-- 订单详情 -->
      <div class="topInfoBox">
        <div class="infoLeft">
          <div class="item">下单时间：{{$moment(orderDetail.create_time*1000).format('YYYY/MM/DD  HH:mm:ss')}}</div>
          <div class="item">客户名称：{{orderDetail.nickname}}</div>
          <div class="item">订单来源：APP商城</div>
          <div class="item flex" style="padding-right:20px;"><span style="flex-shrink:0;">订单备注：</span>{{orderDetail.remark}}</div>
        </div>
        <div class="infoRight">
          <div class="item">商品数量：{{orderDetail.num}}款</div>
          <div class="item" v-if="orderDetail.delivery_type == 2">订单状态：<span style="color:#66A4E3;">{{orderDetail.status==0?'已取消':orderDetail.status==1?'待付款':orderDetail.status==2?'待发货':orderDetail.status==3?'待核销':orderDetail.status==4?'已完成':''}}</span></div>
          <div class="item" v-else>订单状态：<span style="color:#66A4E3;">{{orderDetail.status==0?'已取消':orderDetail.status==1?'待付款':orderDetail.status==2?'待发货':orderDetail.status==3?'待收货':orderDetail.status==4?'已完成':''}}</span></div>
          <div class="item" v-if="orderDetail.delivery_type == 2 && orderDetail.status == 3">核销码：{{orderDetail.pick_code}} <a-button style="margin-left:10px;" type="primary" size="small" @click="createQrCode(orderDetail.pick_code)">生成二维码</a-button></div>
          <div class="item" v-if="orderDetail.delivery_type == 2">自提点：{{orderDetail.pick.store_name}} {{orderDetail.pick.address?`（${orderDetail.pick.address}）`:''}}</div>
          <div class="item" v-if="orderDetail.delivery_type == 2">预留电话：{{orderDetail.pick_mobile}}</div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="goodsBox">
        <div class="item" v-for="(item,index) in orderDetail.product_list" :key="index">
          <div class="goodsInfo">
            <div style="display:flex;">
              <div class="left">商品名称：<span>{{item.product_title}}</span></div>
              <!-- <div class="left">库存：<span>{{item.num}}</span></div> -->
              <div class="left">单位：<span>{{item.spec_unit}}</span></div>
            </div>
            <!-- <div style="display:flex;">
              <div class="right">信息费比例：<span>24%</span></div>
              <div class="right">信息费：<span>￥24.00</span></div>
              <div class="right">获得积分：<span>36分</span></div>
            </div> -->
          </div>
          <div class="goodsOrderInfo">
            <div class="imgBox">
              <img :src="item.logo" alt="">
              <div>
                <div>规格：{{item.spec_volume}}</div>
                <div style="padding:8px 0;">生产企业：{{item.manufacturer}}</div>
                <div>商品种类：{{item.drug_type==1?'普通药品':item.drug_type==2?'保健品':item.drug_type==3?'医疗器械':item.drug_type==4?'中药类':''}}</div>
              </div>
            </div>
            <div class="priceBox">
              <div class="item">￥{{(orderDetail.sale_price/item.num).toFixed(2)}}<p>单价</p></div>
              <div class="item">{{item.num}}件<p>数量</p></div>
              <div class="item">￥{{item.sale_price}}<p>合计</p></div>
              <!-- <div class="item">￥7600.00<p>应到账</p></div> -->
              <div class="item">{{item.code}}<p>商品编码</p></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 发货信息 && 支付信息 -->
      <div class="sendMsg" v-if="orderDetail.delivery_type == 1">
        <h4>发货信息</h4>
        <div class="infoBox">
          <div class="item">
            <div><span>收货人名称：</span>{{orderDetail.name}}</div>
            <div class="mItem"><span>收货人电话：</span>{{orderDetail.mobile}}</div>
            <div><span>收货地址：</span>{{orderDetail.province}}{{orderDetail.city}}{{orderDetail.district}}{{orderDetail.address}}</div>
          </div>
          <!-- <div class="item">
            <div><span>发票抬头：</span>{{orderDetail.invoice?orderDetail.invoice.company:''}}</div>
            <div class="mItem"><span>税号：</span>{{orderDetail.invoice?orderDetail.invoice.taxpayer_code:''}}</div>
            <div class="btnItem"><div><span>发票状态：</span><span v-if="orderDetail.invoice">{{orderDetail.invoice.status==0?'未出票':orderDetail.invoice.status==1?'已出票':orderDetail.invoice.status==2?'已换票':orderDetail.invoice.status==3?'无发票':''}}</span></div><a-button v-if="orderDetail.invoice" type="primary" @click="toChangeInvoice(orderDetail.invoice.id)">更换发票</a-button></div>
          </div> -->
        </div>
      </div>
      <div class="sendMsg">
        <h4>支付信息</h4>
        <div class="infoBox">
          <div class="item">
            <div><span>支付方式：</span>{{orderDetail.pay_type==1?'微信支付':orderDetail.pay_type==2?'支付宝':orderDetail.pay_type==3?'快捷支付':orderDetail.pay_type==4?'余额支付':''}}</div>
            <div class="mItem"><span>订单总价：</span>￥{{orderDetail.sale_price}}</div>
          </div>
          <div class="item">
            <!-- <div><span>信息费：</span>￥24000</div>
            <div class="mItem"><span>应到账：</span>￥76000.00</div> -->
          </div>
        </div>
      </div>

      <!-- 按钮组 -->
      <div class="BtnBox">
        <!-- <a-button type="primary">确认该订单</a-button> -->
        <a-button type="primary" v-if="orderDetail.status==2" @click="sendBtn">发货</a-button>
        <a-button type="primary" size="small" v-if="orderDetail.status == 3 || orderDetail.status == 4" @click="viewExpress">查看物流</a-button>
        <!-- <a-button type="primary">打印仓库取货单</a-button> -->
        <!-- <a-button style="background:#FEAE4D;color:#fff;">打印发货单</a-button> -->
      </div>
    </div>

    <!-- 发货弹出 -->
    <a-modal
      title="订单发货"
      v-if="visible"
      v-model="visible"
      :width="520"
      :centered="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="expressBox">
        <div>
          <span>发货方式：</span>
          <a-button @click="selectExpressType(2)" style="margin-left:20px;" :type="express_type==2?'primary':''" shape="round">自配送</a-button>
          <a-button @click="selectExpressType(1)" style="margin-left:20px;" :type="express_type==1?'primary':''" shape="round">快递配送</a-button>
        </div>
        <div v-if="express_type==1">
          <div style="margin:30px 0 20px;">
            <span>快递公司：</span>
            <a-select
              v-model="express_id"
              @popupScroll="popupScroll"
              show-search
              @search="SearchOrderExpress"
              @change="selectExpress"
              option-filter-prop="children"
              placeholder="请选择快递公司"
              style="width: 50%"
              allowClear
            >
              <a-select-option
                :value="item.id"
                v-for="(item, index) in expressList"
                :key="index"
                >{{ item.title }}</a-select-option
              >
            </a-select>
          </div>
          <div>
            <span>快递单号：</span>
            <a-input style="width: 50%;" placeholder="请输入快递单号" v-model="express_no"></a-input>
          </div>
        </div>
      </div>
    </a-modal>

    
    <a-modal
      v-model="visibleExpress"
      :width="650"
      :closable="false"
      :centered="true"
      :maskClosable="false"
      @ok="handleCancelExpress"
      @cancel="handleCancelExpress"
    >
      <div>
        <a-timeline>
          <a-timeline-item v-for="(item,index) in expressData" :key="index">
            <div class="flex align-center" style="margin-bottom:10px;">
              <h3 style="margin:0">{{item.status}}</h3>
              <div style="margin-left:20px;">{{item.time}}</div>
            </div>
            <p>{{item.context}}</p>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-modal>

    <a-modal
      v-model="visibleQrCode"
      :width="180"
      :closable="false"
      :centered="true"
      :maskClosable="false"
      @ok="handleCancelQrCode"
      @cancel="handleCancelQrCode"
    >
      <div class="qrcode" ref="qrCodeUrl"></div>
    </a-modal>

  </div>
</template>

<script>
import { showErrors, showError, showSuccess } from '@/utils/showMsg';
import { OrderDetail, GetOrderExpress, OrderSend, getExpressInfo } from '@/api/api.js';
import QRCode from 'qrcodejs2';
export default {
  data() {
    return {
      orderDetail:{},
      visible:false,
      expressList:[],

      express_type:1, //1-自配送，2-快递
      express_id:undefined, //选择的快递公司id
      express_no:'', //快递单号

      visibleExpress: false, // 物流信息弹框
      expressData:[], //物流信息数据

      visibleQrCode:false,//核销二维码弹窗
    };
  },
  mounted() {
    const that = this;
    that.GetOrderDetail()
  },
  methods: {
    // 生成核销二维码
    createQrCode(code){
        this.visibleQrCode = true
        this.$nextTick(()=>{
          let qrcode = new QRCode(this.$refs.qrCodeUrl, {
              text: code, // 需要转换为二维码的内容
              width: 110,
              height: 110,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H
          })
        })
    },
    // 关闭二维码弹出
    handleCancelQrCode(){
      this.visibleQrCode = false
      this.$refs.qrCodeUrl.innerHTML=''
    },

    // 获取订单详情
    async GetOrderDetail(){
      let that = this;
      let id = that.$route.query.id;
      let res = await OrderDetail({id})
      if(res.data.code == 1){
        let data = res.data.data
        that.orderDetail = data
      }else{
        showError(res.data.msg)
      }
    },

    
    // 搜索快递公司
    SearchOrderExpress(e) {
      const that = this;
      console.log(e, "==");
      that.GetOrderExpress('',e)
    },

    // 获取快递公司列表
    async GetOrderExpress(type, keyword) {
      const that = this;
      if (type == "more") {
        that.page++;
      } else {
        that.page = 1;
      }
      let params = {
        keyword,
        page: that.page,
        pagesize: that.pagesize,
      };
      let res = await GetOrderExpress(params);
      if (res.data.code == 1) {
        let data = res.data.data;
        if (type == "more") {
          that.expressList = that.expressList.concat(data);
        } else {
          that.expressList = data;
        }
      }
    },

    // 下拉快递公司加载更多
    popupScroll(e) {
      const that = this;
      const { target } = e;
      const { scrollTop, scrollHeight, clientHeight } = target;

      if (scrollTop + clientHeight == scrollHeight) {
        // 已经到达底部，触发分页逻辑
        // todo 这里就可以触发加载下一页请求  具体函数根据当前业务需求来定
        that.GetOrderExpress('more')
      }
    },


    // 发货按钮
    sendBtn(){
      const that = this;
      // if(that.orderDetail.delivery_type == 1){
        that.visible = true;
        that.GetOrderExpress() //物流
      // }else{
      //   that.selfLift() //自提
      // }
      
    },

    // 自提订单发货
    async selfLift(){
      const that = this;
      // that.$confirm({
      //   content: '该订单确定要发货吗？',
      //   okText: '确认',
      //   cancelText: '取消',
      //   async onOk(){
      //     let id = that.$route.query.id;
      //     let res = await OrderSend({id})
      //     if(res.data.code == 1){
      //       showSuccess('发货成功')
      //       that.GetOrderDetail()
      //     }else{
      //       showError(res.data.msg)
      //     }
      //   }
      // });
      
      that.$confirm('该订单确定要发货吗？','提示',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type:'warning'
      }).then(async ()=>{
          let id = that.$route.query.id;
          let res = await OrderSend({id})
          if(res.data.code == 1){
            showSuccess('发货成功')
            that.GetOrderDetail()
          }else{
            showError(res.data.msg)
          }
      })
    },

    // 选择自配送还是快递
    selectExpressType(type){
      const that = this;
      that.express_type = type;
    },

    // 选择快递公司
    selectExpress(){
      const that = this;
      console.log(that.expressValue);
    },

    // 发货弹窗确定
    async handleOk(){
      const that = this;
      if(that.express_type == 1){
        if(!that.express_id){
          showError('请选择快递公司')
          return
        }
        if(that.express_no==''){
          showError('请输入快递单号')
          return
        }
      }
      let id = that.$route.query.id;
      let params = {
        id,
        express_type:that.express_type,
        express_id:that.express_id,
        express_no:that.express_no
      }
      let res = await OrderSend(params)
      if(res.data.code == 1){
        showSuccess('发货成功')
        that.GetOrderDetail()
        that.handleCancel()
      }else{
        showError(res.data.msg)
      }
    },
    // 发货弹窗取消
    handleCancel(){
      const that = this;
      that.visible = false;
      that.express_type = 1;
      that.express_id = undefined;
      that.express_no = ''
    },

   // 更换发票按钮
   toChangeInvoice(id){
      const that = this;
      that.$router.push({name:'invoiceDetail',query:{id}})
   },
  
    // handleCancelExpress 物流信息弹出取消
    handleCancelExpress(){
      const that = this;
      that.visibleExpress = false;
    },

    // 查看物流按钮
    async viewExpress(){
      const that = this;
				if(!that.orderDetail.express_no){
					showError('单号为空')
					return
				}
				if(!that.orderDetail.express_code){
					showError('快递公司为空')
					return
				}
        
				let params = {
					// express_code:'zhongtong', //快递公司编码
					// express_no:'78846266018814', //快递单号
					express_code: that.orderDetail.express_code,
					express_no: that.orderDetail.express_no,
          phone: that.orderDetail.mobile
				};
				let res = await getExpressInfo(params)
				console.log(res,'res')
				if(res.data.code == 1){
          let data = res.data.data;
          if(data.status == 200){
            that.expressData = res.data.data.data;
            that.visibleExpress = true;
          }else{
					  showError(data.message)
          }
				}else{
					showError(res.data.msg)
				}
        // window.open(`https://www.kuaidi100.com/chaxun?com=${param.com}&nu=${param.num}`);
    }
  }

};
</script>

<style scoped lang="stylus">
.editable-row-operations a {
  margin-right: 12px;
}
.Main {
  border-radius: 10px;
  overflow: hidden;
  background: #fff;
  .MainTitle {
    font-size: 24px;
    color: #333;
    margin: 10px 20px;
    position: relative;
  }
  .MainTitle:before {
    
    content: '';
    width: 40px;
    height: 12px;
    background: linear-gradient(270deg, rgba(0, 158, 238, 0) 0%, rgba(0, 158, 238, 0.3) 100%);
    position: absolute;
    bottom: 2px;
    left: 0;
  }
  .MianContent {
    padding: 10px 20px 20px 20px;
    .MainTopAction {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .MainTopActionView {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .MainTopActionOne {
          margin-right: 30px;
          span {
            margin-right: 20px;
          }
        }
        .MainTopActionTwo {
          span {
            margin-right: 20px;
          }
        }
      }
      .MainTopActionThree {
        display: flex;
        align-items: center;
        margin-left: 20px;
      }
    }
  }

  // 订单详情
  .topInfoBox{
    display: flex;
    // align-items: center;
    padding-bottom: 20px;
    border-bottom: 1px solid #EEEEEE;
    .infoLeft{
      width 40%
    }
    .infoRight{
      width 60%
    }
  }

  // 商品列表
  .goodsBox{
    padding-bottom: 8px;
    border-bottom: 1px solid #DCDFE6;
    .item{
      border: 1px solid #DAE0E0;
      margin-bottom:10px;
      .goodsInfo{
        padding: 0 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #F5F5F5;
        height:40px;
        span{
          color: #333333;
        }
        .left{margin-right:45px;}
        .right{margin-left:17px;}
      }
      .goodsOrderInfo{
        padding: 0 12px;
        display: flex;
        align-items: center;
        .imgBox{
          display: flex;
          align-items: center;
          padding: 12px 0;
          width: 25%;
          font-size:12px;
          img{
            width:80px;
            height:80px;
            margin-right: 10px;
            flex-shrink: 0;
          }
        }
        .priceBox{
          width 75%;
          display: flex;
          .item{
            margin: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            border:0;
            text-align: center;
            width: 20%;
            height 108px;
            border-left: 1px solid #DAE0E0;
            p{margin: 0;}
          }
        }
      }
    }
  }

  // 发货信息 & 支付信息
  .sendMsg{
    padding: 18px 0 12px 0;
    border-bottom: 1px solid #DCDFE6;
    .infoBox{
      display: flex;
      .item{
        width 50%;
        span{
          display: inline-block;
          width 84px;
          margin-right: 10px;
        }
        .mItem{
          margin: 10px 0;
        }
        .btnItem{
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }

  // 安钮
  .BtnBox{
    margin: 25px 0 ;
    display: flex;
    justify-content: center;
    .ant-btn{
      margin-right: 20px;
    }
  }
}
</style>